package com.the4man.framework.util;

import com.opensymphony.xwork2.ActionContext;
import com.the4man.framework.pagemodel.PUser;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * Created by lenovo on 2017/12/12.
 */
public class RequestUtil {
    private RequestUtil() {
    }

    public static void putOgnlObject(String key, Object value) {
        if(value != null) {
            ActionContext.getContext().put(key, value);
        }

    }

    public static void putSessionObject(String key, Object value) {
        Map<String, Object> session = ActionContext.getContext().getSession();
        session.put(key, value);
    }

    public static Object getSessionObject(String key) {
        Map<String, Object> session = ActionContext.getContext().getSession();
        return session.get(key);
    }

    public static void putHttpSessionObject(String key, Object value) {
        HttpSession session = ServletActionContext.getRequest().getSession(true);
        session.setAttribute(key, value);
    }

    public static Object getHttpSessionObject(String key) {
        HttpSession session = null;

        try {
            session = ServletActionContext.getRequest().getSession(true);
        } catch (Exception var3) {
            ;
        }

        return session == null?null:session.getAttribute(key);
    }

    public static void removeSessionObject(String key) {
        HttpSession session = ServletActionContext.getRequest().getSession(true);
        session.removeAttribute(key);
    }

    public void killHttpSession() {
        HttpSession session = ServletActionContext.getRequest().getSession(true);
        if(session != null) {
            session.invalidate();
        }

    }

    public static String getlogserialnumber() {
        return getUserSessionObject().getLogserialnumber();
    }

    public static PUser getUserSessionObject() {
        PUser user = getHttpSessionObject(InitParamUtil.getSessionInfoName()) == null?null:(PUser)getHttpSessionObject(InitParamUtil.getSessionInfoName());
        return user;
    }

    public static String getParameterStr(String name) {
        String parameter = ServletActionContext.getRequest().getParameter(name);
        return parameter == null?"":parameter;
    }

    public void putParameterStr(String name, Object value) {
        ServletActionContext.getRequest().setAttribute(name, value);
    }

    public static int getParameterNum(String name, int def) {
        String num = ServletActionContext.getRequest().getParameter(name);
        return num != null && !"".equals(num.trim())?Integer.parseInt(num.trim()):def;
    }

    public static PUser getSessionUserinfo() {
        return (PUser)getHttpSessionObject(InitParamUtil.getSessionInfoName());
    }
}
